<!DOCTYPE html
  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>惠聚海报</title>
  <style type="text/css">
    body {
      margin-left: 0px;
      margin-top: 0px;
      background-color: #ccc
    }

    .div {
      margin: 5px auto;
      width: 640px;
      height: 1046px;
      background-color: #fff;
      background-image: url(bg01.jpg);
      background-size: 100% 100%;
    }

    .t1 {
      float: left;
      width: 100%;
      margin: 97px 0 0 0;
      text-align: center;
      font-family: "思源黑体";
      font-size: 68px;
      color: #e50d36;
      font-weight: 700
    }

    .t2 {
        float: left;
        width: 560px;
        height: 60px;
        margin: 23px 0 5px 40px;
        text-align: center;
        font-family: "思源黑体";
        font-size: 38px;
        color: #000;
        font-weight: 200;
        overflow: hidden;
    }

    .pic {
      float: left;
      width: 593px;
      margin: 18px 0 0 23px;
      height: 378px;
      /* background-color: #fbfbf6; */
      overflow: hidden;
      text-align: center;
    }

    .pic img {}

    .t3 {
      float: left;
      text-align: right;
      width: 180px;
      height: 134px;
      font-size: 30px;
      line-height: 155px;
      overflow: hidden;
      color: #e60d29;
      font-family: "思源黑体";
      font-weight: 200;
    }

    .t4 {
      float: left;
      height: 134px;
      font-size: 60px;
      line-height: 134px;
      overflow: hidden;
      color: #e60d29;
      font-family: "思源黑体";
      font-weight: 700;
    }

    .t5 {
      float: left;
      height: 134px;
      padding-left: 20px;
      font-size: 30px;
      line-height: 155px;
      overflow: hidden;
      color: #e60d29;
      font-family: "思源黑体";
      font-weight: 200;
      text-decoration: line-through;
      overflow: hidden
    }

    .div2 {
      float: left;
      width: 580px;
      height: 165px;
      margin: 5px 0 0 31px;
    }

    .khm {
      float: right;
      width: 147px;
      height: 147px;
      overflow: hidden;
      margin: 8px 43px 0 0;
      background-color: #fff;
      border-radius: 50%;
    }

    .khm img {
      width: 100%;
    }

    .editor {
      position: absolute;
      left: 0;
      top: 0;
      z-index: 999;
      background-color: #FFF;
      padding: 10px;
    }
  </style>
</head>

<body>
  <div class="div" id="main">
    <div class="t1" id="t1_field">4层加厚，温水柔韧</div>
    <div class="t2" id="t2_field">商品名称商品名称</div>
    <div class="pic">
      <img src="img.jpg" id="picsrc" width="378" height="378" />
    </div>

    <span class="t3">秒杀价￥</span>
    <span class="t4" id="t4_field">999.99</span>
    <span class="t5" id="t5_field">市场价￥99.99</span>
    <div class="div2">
      <div class="khm">
        <img src="khm.png" id="code" width="147" height="147" />
      </div>
    </div>
  </div>
  <div class="editor">
    <div>
      <label>大标题：<input id="t1" value="" /></label>
    </div>
    <div>
      <label>商品名：<input id="t2" value="" /></label>
    </div>
    <div>
      <label>秒杀价：<input id="t4" value="" /></label>
    </div>
    <div>
      <label>市场价：<input id="t5" value="" /></label>
    </div>
    <div>
      <label>商品图：<input id="t6" value="" /></label>
    </div>
    <div>
      <label>小程序：<input id="xcx" value="" /></label>
    </div>
    <div>
      <label>参数：<input id="chan_id" value="6363" /></label>
    </div>
    <div>
      <label>json：<textarea id="t7" cols="30" rows="10"></textarea></label>
    </div>
    <div>
      <button onclick="createAd()">生成海报</button>
    </div>
    <div>
        ----------------
    </div>
    <div>
        <label for="spuId">spu_id:<input id="t8" value=""/></label>
    </div>
    <div>
      <button onclick="searchGoods()">抓取单品</button>
    </div>
  </div>
  <div id="main2">
  </div>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/html2canvas/0.5.0-beta4/html2canvas.min.js"></script>
<script src="./canvas2image.js"></script>
<script>
  var fileName = ""
  $("#t1").change(function () {
    $("#t1_field").text($("#t1").val())
  })
  $("#t2").change(function () {
    $("#t2_field").text($("#t2").val())
    fileName = $("#t2").val()
  })
  $("#t4").change(function () {
    $("#t4_field").text($("#t4").val())
  })
  $("#t5").change(function () {
    $("#t5_field").text("市场价￥" + $("#t5").val())
  })
  $("#t6").change(function () {
    $("#picsrc").attr("src", $("#t6").val())
  })

  $("#t7").change(function () {
    let data = JSON.parse($("#t7").val())
    // console.log(data)
    showView(data.data)
  })
  $("#chan_id").change(function(){
      if(data){
          showView(data)
      }
  })

  var showView = function (data) {
    // console.log(data)
    let pic_url = ''
    let mainImgUrl = ''
    let url = ''
    let chan_id = $("#chan_id").val()
    if (data.spuInfo) {
      mainImgUrl = data.spuInfo.mainImgUrl
      $("#t2").val(data.spuInfo.name)
      $("#t4").val(number_format(data.spuInfo.showPrice / 100, 2, ".", ","))
      $("#t5").val(number_format(data.spuInfo.marketPrice / 100, 2, ".", ","))
      $("#t1").val(data.merchantInfo.name)
      $("#t8").val(data.spuInfo.spuId)
      url = "pages/item-detail/index?id=" + data.spuInfo.spuId + "&chan_id="+chan_id
    } else if (data.spu) {
      mainImgUrl = data.spu.mainImgUrl
      $("#t2").val(data.spu.name)
      $("#t4").val(number_format(data.spu.showPrice / 100, 2, ".", ","))
      $("#t5").val(number_format(data.spu.marketPrice / 100, 2, ".", ","))
      $("#t1").val(data.merchant.name)
      $("#t8").val(data.spu.spuId)
      url = "pages/item-detail/index?id=" + data.spu.spuId + "&chan_id="+chan_id
    }
    if(isJSON(mainImgUrl)){
        
        let picArr = JSON.parse(mainImgUrl)
        if (typeof picArr == "object") {
          pic_url = picArr.o
        } 
    }else {
      pic_url = mainImgUrl.replace("218", "400")
    }

    $.post({
      url: "/gethjcode.php",
      type: "post",
      data: { "path": url },
      success: function (res) {
        let result = JSON.parse(res)
        if (result.base_resp.ret == 0) {
          // window.open("/tools/huiju/getimage.php?data="+result.qrcode_url)
          getBase64ImageUrl("/getimage.php?data="+result.qrcode_url, function (url) {
            $("#code").attr("src", url)
          })
        }else{
          alert("获取葵花码失败："+result.base_resp.err_msg)
        }
      }
    })

    $("#picsrc").attr("src", pic_url)
    $("#t6").val(pic_url)
    $("#xcx").val(url)
    $("#t1").change()
    $("#t2").change()
    $("#t4").change()
    $("#t5").change()
    $("#t6").change()
    getBase64ImageUrl(pic_url, function (url) {
      $("#picsrc").attr("src", url)
    })
  }
  
  let params = location.search.substring(1)
  let data = decodeURI(params.replace('data=', ''))
  if(isJSON(data)){
      data = JSON.parse(data)
      $("#t7").val(JSON.stringify(data))
      showView(data)
  }

  function isJSON(str) {
    if (typeof str == 'string') {
      try {
        var obj = JSON.parse(str);
        if (typeof obj == 'object' && obj) {
          return true;
        } else {
          return false;
        }

      } catch (e) {
        console.log('error：' + str + '!!!' + e);
        return false;
      }
    }
    // console.log('It is not a string!')
  }
  /**
   *  价格格式化
   */
  function number_format(number, decimals, dec_point, thousands_sep) {
    /*
    * 参数说明：
    * number：要格式化的数字
    * decimals：保留几位小数
    * dec_point：小数点符号
    * thousands_sep：千分位符号
    * */
    number = (number + '').replace(/[^0-9+-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
      prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
      sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
      dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
      s = '',
      toFixedFix = function (n, prec) {
        var k = Math.pow(10, prec);
        return '' + Math.ceil(n * k) / k;
      };

    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    var re = /(-?\d+)(\d{3})/;
    while (re.test(s[0])) {
      s[0] = s[0].replace(re, "$1" + sep + "$2");
    }

    if ((s[1] || '').length < prec) {
      s[1] = s[1] || '';
      s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
  }
  // 保存海报
  var createAd = function () {
    html2canvas(document.getElementById('main'), {
      width: 640,
      height: 1046,
      onrendered: function (canvas) {
        // canvas.setAttribute("id", 'thecanvas')
        // //读取属性值
        // // var value= canvas.getAttribute('id');
        // oCanvas = canvas.getContext("2d")
        // let src = canvas.toDataURL('image/jpeg', 1)
        // console.log(src)
        // document.getElementById('main2').appendChild(canvas);
      },
      ignoreElements: (element) => { // 忽略不被绘制的dom元素
        return element.className === 'tool product-view-tool'
      }
    }).then(canvas => {
      oCanvas = canvas.getContext("2d")
      let src = canvas.toDataURL('image/jpeg', 1)
      let image = new Image()
      image.src = src
      let url = image.src.replace(/^data:image\/[^;]/, 'data:application/octet-stream')
      let a = document.createElement('a')
      a.download = fileName + '.jpg' // 设置下载的文件名，默认是'下载'
      a.href = url
      document.body.appendChild(a)
      a.click()
      a.remove() // 下载之后把创建的元素删除
    })
  }
  // 远程图片转64base
  function getBase64ImageUrl(url, callBack, imgType) {
    if (!imgType) {
      imgType = "image/jpeg";
    }
    var img = new Image();
    img.src = url;
    img.crossOrigin = "anonymous";
    img.onload = function () {
      var canvas = document.createElement("canvas");
      canvas.width = img.width
      canvas.height = img.height
      var ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, img.width, img.height);
      var dataURL = canvas.toDataURL(imgType);
      callBack(dataURL);
    }
  }
  var searchGoods = function (){
      $.ajax({
          url:"/getGoods.php",
          data:"id="+$("#t8").val(),
          success:function(result){
              let res = JSON.parse(result)
              
              if(res.code == 0){
                  showView(res.data)
              }
          }
      })
  }
</script>

</html>